package front

import activity.*
import history.*
import groovy.sql.*
import org.joda.time.*

class CalendarController {
    def dataSource

    def sql() {
        def db = new Sql(dataSource)
        def results = db.rows("SELECT * FROM Event")
        for(row in results) {
            print row.name
            println row
        }
        //[result: result]
        render "SQL Index"
    }
    
    def index() {
        if (!params.yearmonth) {
            def now = new DateTime()
            params.yearmonth = now.year + "-" + now.monthOfYear
        }
        //找出月初、月底
        def (year, month) = params.yearmonth.tokenize('-')
        def monthStart = new DateTime(year.toInteger(), month.toInteger(), 1, 0, 0, 0, 0)
        def monthEnd = monthStart.plus(Period.months(1)).plus(Period.days(-1))
//println "monthStart:"+monthStart
//println "monthEnd:"+monthEnd
        def prevMonth = monthStart.plus(Period.months(-1))
        def newMonth = monthStart.plus(Period.months(1))
        def thisMonth = monthStart.getYear() + '-' + monthStart.getMonthOfYear()
        def lastMonth = prevMonth.getYear() + '-' + prevMonth.getMonthOfYear()
        def nextMonth = newMonth.getYear() + '-' + newMonth.getMonthOfYear()
//        println "thisMonth:"+thisMonth
        //找出之間場次
        def query = Event.where {
            (dateStart >= monthStart.toDate() && dateStart <= monthEnd.toDate()) || 
            (dateEnd >= monthStart.toDate() && dateEnd <= monthEnd.toDate()) || 
            (dateStart >= monthStart.toDate() && dateEnd <= monthEnd.toDate())
        }
        def events = query.list()
//        println "eventSize:" + events.size()
        //匯成Map(日:活動ID)
        def calMap = [:]
        def day, serials
        for (event in events) {
            day = new DateTime(event.dateStart).dayOfMonth
            serials = calMap.get(day)
            if (serials) {
                serials.add(event.serial.id)
            } else {
                calMap.put(day, [event.serial.id])
            }
        }
        //移除重覆serial並排序
        for (entry in calMap) {
            entry.value = entry.value.toSet().sort()
        }
//println "calMap:" + calMap
        //依星期調整第一天
        //println "Mon\tTue\tWed\tThu\tFri\tSat\tSun"
        def output = "<tr>"<<''
        for (int i = 1; i < monthStart.dayOfWeek; i++) {
            //print("t\t");
            output << "<td>　</td>"
        }
        
        def calDay = monthStart
        def dayText
        def mapDay
//println "MS:"+monthStart.dayOfMonth
//println "ME:"+monthEnd.dayOfMonth
        for (def i = monthStart.dayOfMonth; i <= monthEnd.dayOfMonth; i++) {
            mapDay = calMap.get(calDay.dayOfMonth)
            if (mapDay) {
                dayText = remoteLink(action:'serials', params:[serials:mapDay.join("-")], update:"serials", {calDay.dayOfMonth})
            } else {
                dayText = calDay.dayOfMonth
            }
//println "dayOfMonth:"+calDay.dayOfMonth
//println "mapDay:"+mapDay
//println "dayText:"+dayText
            if (calDay.dayOfWeek == 7) {
                //print calDay.date  + "("+ getWeek(calDay) + ")" + "r\r"
                output << "<td>" + dayText + "</td></tr>\r<tr>"
            } else {
                //print calDay.date + "("+ getWeek(calDay) + ")" + "t\t"
                output << "<td>" + dayText + "</td>"
            }
            calDay = calDay.plus(Period.days(1))
        }
        //補表尾
        calDay = calDay.plus(Period.days(-1))
        for (int i = 1; i <= 7 - calDay.dayOfWeek; i++) {
            //print("t\t");
            output << "<td>　</td>"
        }
        output << "</tr>"
        [calendar:output, thisMonth:thisMonth, lastMonth:lastMonth, nextMonth:nextMonth]
    }
    
    def serials() {
        def serialIds = params.serials.split("-")
//        println "serialIds:"+serialIds
        def billboardList = Billboard.findAllByDateStartLessThanEqualsAndDateEndGreaterThanEquals(
            new Date(), new Date())
        def query = Serial.where {
            id in serialIds*.toLong()
        }
        def serialList = query.list()
//        println "serialList:"+serialList
        [serialInstanceList: serialList, serialInstanceTotal: serialList.size(),
            billboardList: billboardList]
    }    
}
